<?php

namespace Admin\Controller;

use Org\Util\String;

class ModMemberController extends ModController
{
    static $export_menu = array(
        'user' => array(
            '用户信息' => array(
                'userlist' => array(
                    'title' => '系统会员',
                    'hiddens' => array(
                        'userview' => '系统会员查看',
                        'userhandle' => '系统会员管理'
                    )
                )
            )
        )
    );

    public function build($yummy = false)
    {
        parent::build($yummy);

        switch ($this->build_db_type) {
            case 'mysql' :

                $sqls = array();

                if (!$this->build_table_exists("member_user")) {
                    $table_name = $this->build_db_prefix . "member_user";
                    $sqls [] = "DROP TABLE IF EXISTS `$table_name`";
                    $sqls [] = "
								CREATE TABLE `$table_name` (
									`uid` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '用户UID',
									`email` CHAR(100) NOT NULL DEFAULT '' COMMENT '邮箱',
									`cellphone` CHAR(20) NOT NULL DEFAULT '' COMMENT '手机',
									`username` CHAR(20) NOT NULL DEFAULT '' COMMENT '用户名',
									`password` CHAR(32) NOT NULL DEFAULT '' COMMENT '密码MD5值',
									`password_salt` CHAR(10) NOT NULL DEFAULT '' COMMENT '密码Salt',
									`reg_time` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '注册时间',
									`reg_ip` BIGINT NOT NULL DEFAULT 0 COMMENT '注册IP',
									`lastlogin_time` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '上次登录时间',
									`lastlogin_ip` BIGINT NOT NULL DEFAULT 0 COMMENT '上次登录IP',
									`email_status` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '邮箱状态 0未验证 1已验证',
									`cellphone_status` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '手机状态 0未验证 1已验证',
									`avatar_status` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '头像状态 0无头像 1有头像',
									
									`member_status` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '账户状态  0正常 1锁定 2自动注册的可以初始化登录',
									" . (defined('TPX_VERSION') ? "" : "`gid` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '用户组（1.0.0开始废弃）',
									
									`cnt_msg` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '新消息条数（1.0.0开始废弃）',
									`cnt_friend` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '朋友个数（1.0.0开始废弃）',
									`cnt_follow` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '关注别人的数（1.0.0开始废弃）',
									`cnt_be_followed` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '被别人关注数（1.0.0开始废弃）',
									") . "

									PRIMARY KEY (`uid`),
									KEY `email`(`email`),
									KEY `cellphone`(`cellphone`),
									KEY `username`(`username`)
									
								) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT '用户基本信息表';
								";
                }

                if (!$this->build_table_exists("member_bind")) {
                    $table_name = $this->build_db_prefix . "member_bind";
                    $sqls [] = "DROP TABLE IF EXISTS `$table_name`";
                    $sqls [] = "
								CREATE TABLE `$table_name` (
                                    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
								    `uid` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '用户ID',
								    `type` VARCHAR(50) NOT NULL DEFAULT '' COMMENT 'Bind类型',
								    `content` VARCHAR(200) NOT NULL DEFAULT '' COMMENT '正文内容',
									PRIMARY KEY (id),
								    KEY `uid`(`uid`),
								    KEY ix_type_content(type,content)
								) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT '用户绑定信息表';
								";
                }

                if (!defined('TPX_VERSION')) {
                    if (!$this->build_table_exists("member_follow")) {
                        $table_name = $this->build_db_prefix . "member_follow";
                        $sqls [] = "DROP TABLE IF EXISTS `$table_name`";
                        $sqls [] = "
								CREATE TABLE `$table_name` (
								`uid` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '用户ID',
								`fuid` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '关注用户的ID',
								
								KEY `uid`(`uid`),
								KEY `fuid`(`fuid`)
									
								) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT '用户关注表（1.0.0开始废弃）';
								";
                    }
                }

                if (!defined('TPX_VERSION')) {
                    if (!$this->build_table_exists("member_msg")) {
                        $table_name = $this->build_db_prefix . "member_msg";
                        $sqls [] = "DROP TABLE IF EXISTS `$table_name`";
                        $sqls [] = "
								CREATE TABLE `$table_name` (
								`uid` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '接收用户ID',
								`fuid` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '发送用户ID，0表示系统',
								`sendtime` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '发送时间',
								`isread` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '阅读状态 0未读 1已读',
								`message` VARCHAR(250) NOT NULL DEFAULT '' COMMENT '消息正文',
								
								KEY `uid`(`uid`),
								KEY `fuid`(`fuid`),
								KEY `sendtime`(`sendtime`)
									
								) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT '用户消息表（1.0.0开始废弃）';
								";
                    }
                }

                if (!$this->build_table_exists("member_profile")) {
                    $table_name = $this->build_db_prefix . "member_profile";
                    $sqls [] = "DROP TABLE IF EXISTS `$table_name`";
                    $sqls [] = "CREATE TABLE `$table_name` (
                                id INT UNSIGNED NOT NULL AUTO_INCREMENT,
								`uid` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '用户ID',
								
								`realname` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '真实姓名',
								`gender` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '性别 1男2女0保密',
								`age` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '年龄',
								
								`idcardtype` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '证件类型',
								`idcard` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '证件号',
								
								`job` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '工作',
								`interest` VARCHAR(200) NOT NULL DEFAULT '' COMMENT '兴趣',
								
								`qq` VARCHAR(20) NOT NULL DEFAULT '' COMMENT 'QQ',
								`wechat` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '微信',
												
								`birth_year` SMALLINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '出生年',
								`birth_month` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '出生月',
								`birth_day` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '出生日',

								addr_country VARCHAR(20) NOT NULL DEFAULT '' COMMENT '国家',
								`addr_province` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '省',
								`addr_city` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '市',
								`addr_dist` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '区',
								`addr_community` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '街区',
								`addr_detail` VARCHAR(200) NOT NULL DEFAULT '' COMMENT '详细',
								
                                PRIMARY KEY (id),
                                KEY `uid`(`uid`)
									
								) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT '用户补充信息表';
								";
                }

                if (!$this->build_table_exists("member_attr")) {
                    $table_name = $this->build_db_prefix . "member_attr";
                    $sqls [] = "DROP TABLE IF EXISTS $table_name";
                    $sqls [] = "CREATE TABLE $table_name (
                                    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
                                    uid INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '用户ID',

                                    attr VARCHAR(50) NOT NULL DEFAULT '' COMMENT '属性',
                                    value VARCHAR(500) NOT NULL DEFAULT '' COMMENT '值',

                                    PRIMARY KEY (id),
                                    KEY IX_uid(uid),
                                    KEY IX_uid_attr(uid,attr)
								) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT '用户属性';
								";
                }

                break;
        }

        foreach ($sqls as $sql) {
            $this->build_db->execute($sql);
        }

        parent::build_success($yummy);
    }

    public function userlist()
    {
        if (IS_POST) {

            $current = I('post.current', 1, 'intval');
            $rowCount = I('post.rowCount', 10, 'intval');
            $sort = I('post.sort');
            $searchPhrase = I('post.searchPhrase');

            $m = D('MemberUser');

            // pre process
            $where = array();
            if ($searchPhrase) {
                $where ['username'] = array(
                    'LIKE',
                    "%$searchPhrase%"
                );
                $where ['email'] = array(
                    'LIKE',
                    "%$searchPhrase%"
                );
                $where ['cellphone'] = array(
                    'LIKE',
                    "%$searchPhrase%"
                );
                $where ['_logic'] = 'OR';
            }
            $order = null;
            foreach ($sort as $f => $d) {
                $order = "$f $d";
            }
            if (empty ($order)) {
                $order = 'uid ASC';
            }

            // get info
            $total = $m->where($where)->count();
            if ($order) {
                $m->order($order);
            }
            $data = array();
            $list = $m->where($where)->page($current, $rowCount)->select();
            if (empty($list)) {
                $list = array();
            }
            foreach ($list as &$v) {
                $data [] = array(
                    'uid' => $v ['uid'],
                    'username' => $v ['username'],
                    'cellphone' => $v ['cellphone'],
                    'email' => $v ['email'],
                    'reg_info' => date('Y-m-d H:i:s', $v ['reg_time']) . ' / ' . long2ip($v ['reg_ip'])
                );
            }

            $json = array(
                'current' => $current,
                'rowCount' => $total > $rowCount ? $rowCount : $total,
                'total' => $total,
                'rows' => $data
            );
            $this->ajaxReturn($json);
        }
        $this->display();
    }

    public function userview($id = 0)
    {
        $id = intval($id);
        define ('ADMIN_EMPTY_FRAME', true);

        $ms = D('Member', 'Service');

        if (!$ms->init($id)) {
            $this->error('ERR ID');
        }
        if ($ms->get('member.avatar_status')) {
            $this->data_avatar_url = $ms->get_avatar_url(-1, 'b');
        } else {
            $this->data_avatar_url = $ms->get_avatar_url(0, 'b');
        }
        $this->data_user = $ms->get('user.');
        if (!defined('TPX_VERSION')) {
            $this->data_bind = $ms->get('bind.');
            $this->data_follow = $ms->get('follow.');
            $this->data_msg = $ms->get('msg.');
        }
        $this->data_profile = $ms->get('profile.');
        $this->data_id = $id;

        $this->data_upload_space = $ms->get('upload_space.');

        $role_list = array();
        if (has_module('MemberRbac')) {
            $role_list = D('MemberRbacRole')->select();
            if (empty($role_list)) {
                $role_list = array();
            }
        }
        $this->data_roles = $ms->get('rbac_role.');
        $this->data_role_list = $role_list;

        $this->display();
    }

    public function userhandle($action = '', $id = 0)
    {
        $id = intval($id);
        $ms = D('Member', 'Service');

        switch ($action) {
            case 'add':
                if (IS_POST) {
                    $email = I('post.email', '', 'trim');
                    $cellphone = I('post.cellphone', '', 'trim');
                    $username = I('post.username', '', 'trim');
                    $password = I('post.password', '');
                    $ret = $ms->register($email, $cellphone, $username, $password);
                    if (true === $ret) {
                        $this->success('', U(CONTROLLER_NAME . '/userlist'));
                    } else {
                        $this->error($ret);
                    }
                }

                $this->display('userhandle_add');
                break;
            case 'edit' :

                if (!$ms->init($id)) {
                    $this->error('ERR ID');
                }

                // Avatar
                if (I('post.user_avatar_status') == 'deleted') {
                    if (!$ms->enable_avatar(false)) {
                        $this->error('删除头像失败');
                    }
                }

                // Password
                if ($password = I('post.user_password', '', 'trim')) {
                    $msg = $ms->change_password('', $password, $ignore_old = true);
                    if (true !== $msg) {
                        $this->error($msg);
                    }
                }

                // User
                $data = array();
                foreach (array(
                             'username',
                             'email',
                             'cellphone',
                             'member_status',
                             'email_status',
                             'cellphone_status',
                             'gid'
                         ) as $f) {
                    $data [$f] = I('post.user_' . $f);
                }
                if (!$ms->update('user', $data)) {
                    $this->error('更新User失败');
                }

                // Profile
                $data = array();
                foreach (array(
                             'realname',
                             'gender',
                             'age',
                             'idcardtype',
                             'idcard',
                             'interest',
                             'qq',
                             'wechat',
                             'birth_year',
                             'birth_month',
                             'birth_day',
                             'addr_province',
                             'addr_city',
                             'addr_dist',
                             'addr_community',
                             'addr_detail'
                         ) as $f) {
                    $data [$f] = I('post.profile_' . $f);
                }
                if (!$ms->update('profile', $data)) {
                    $this->error('更新Profile失败');
                }

                // Upload
                $data = array();
                if (has_module('MemberUpload')) {
                    $data['space'] = I('post.upload_space_space');
                    $data['space'] = formated_size_to_bytes($data['space']);
                    if (!$ms->update('upload_space', $data)) {
                        $this->error('更新Upload失败');
                    }
                }

                //Rbac
                if (has_module('MemberRbac')) {
                    if (!$ms->update('rbac_role', I('post.roles', array()))) {
                        $this->error('更新Rbac失败');
                    }
                }

                $this->success('更新成功');

                break;
            case 'delete' :
                $ids = array();
                foreach (explode(',', I('post.ids', '', 'trim')) as $id) {
                    $id = intval($id);
                    if ($id) {
                        if ($ms->init($id)) {
                            $ms->delete();
                        }
                    }
                }
                $this->success('OK');
                break;
        }
    }
}